use([
    "public/javascripts/service/order_manageService.js",
    "public/javascripts/widget/slider/slider.js",
    "public/javascripts/widget/prompt/prompt.js",
    "public/javascripts/widget/dialog/dialog.js",
    "public/javascripts/widget/calander/calander.js",
    "public/javascripts/widget/select/select.js",
    "public/javascripts/widget/picPreview/picPreview.js"
], function (order_manageService, SliderComponent, PromptComponent, DialogComponent, Calander, selectFactory, picPreview) {
    var PageComponent = React.createClass({
        componentDidMount: function () {
            //是否是主账号
            var isPrimary = cookie.get('primary') == 'false' ? false : true;
            this.setState({'isPrimary':isPrimary});

            picPreview.init();
            easyMe.useJs(['common/uploadFile/uploadFile.js']);
            Calander.init({
                ele: ['#beginDate', '#endDate'],
                isClear: true
            });
            self.refs.beginDate.setValue(new Date().getBeforeDate(6)+' 00:00:00');
            self.refs.endDate.setValue(new Date().format("yyyy-MM-dd 23:59:59"));

            $("#beginDate").change(function (e) {
                self.refs.beginDate.setValue(e.target.value);
            });
            $("#endDate").change(function (e) {
                self.refs.endDate.setValue(e.target.value);
            });
            this.getSubAccount();
            this.getOrderStatus();
        },
        getInitialState: function () {
            return {
                tabTitle: ['草稿', '已提交', '已受理', '已揽收','运输中','配送中','已签收'],
                active: 1,
                userList: [],
                statusList: [],
                orderStatus: '',
                total: this.props.data.total,
                list: this.props.data.list,
                selectItem: [],
                selectLength: 0,
                orders: [],
                currentTime: '',
                current: 1,
                pageSize: 10,
                showUploadFile:false,
                selectOrderStatus:[],
                selectId:''
            };
        },

        search: function (param) {
            var _this = this;
            if (!param){
                param = {
                    startEffectTime:$('#beginDate').val() || '',
                    endEffectTime:$('#endDate').val() || '',
                    pageIndex: _this.state.current || 1
                };
            }
            if (this.state.userList && param.cusUserId) {
                this.state.userList.forEach(function (item) {
                    if(item.nameCode === param.cusUserId) param.cusUserId = item.id;
                });
            }
            param.statusType = param.statusType ? param.statusType : this.state.active;
            this.state.statusList.forEach(function (item,index) {
                if (index === param.statusType -1) {
                    param.orderStatus = item.code;
                }
            });


            param.sort = 'createTime';
            param.asc = false;
            param.pageSize = param.pageSize ? param.pageSize : this.state.pageSize;
            var _this = this;
            order_manageService.search({ 'urlParams': param }, function (res) {
                if (res.errorCode == 0) {
                    _this.setState({
                        list: res.data,
                        total: res.pagination.totalResult
                    });
                }
            });
        },
        getSubAccount: function () {
            var _this = this;
            order_manageService.getSubAccount('', function (res) {
                if (!res.data) return;
                res.data.forEach(function(item){
                    item.nameCode = item.fullName + '(' + item.userName + ')';
                });
                _this.setState({ userList: res.data });
                selectFactory({
                    data: res,
                    id: "username",
                    isSearch: true,
                    isSaveInputVal:true,
                    pagination: true,
                    searchPlaceHoder: '请输入姓名或用户名',
                    defaultText: '全部',
                    showTextField: 'nameCode',
                    attrTextModel: function (nameCode) {
                        _this.refs.cusUserId.setValue(nameCode);
                    },
                    onSearchValueChange: function(attachEvent, data, currentPage) {
                        order_manageService.getSubAccount({ q: data, pageIndex: currentPage ? currentPage : 1, pageSize:10 }, function (res) {
                            if (!res.data.length) return;
                            res.data.forEach(function(item){
                                item.nameCode = item.fullName + '(' + item.userName + ')';
                            });
                            _this.setState({ userList: res.data });

                            attachEvent.setData(res);
                        });
                    }
                });
            });
        },

        getOrderStatus: function () {
            var _this = this;
            order_manageService.getOrderStatus({}, function (res) {
                if (!res.data) return;
                _this.setState({statusList: res.data});
            });
        },

        getOrdersDetail: function (idArr) {
            var _this = this;
            order_manageService.getOrdersDetail( idArr, function(res) {
                if (res.errorCode === 0) {
                    _this.setState({ orders: res.data });
                    _this.getCurrentTime();
                    res.data.forEach(function(item) {
                        JsBarcode('#barcode_' + item.waybillNo, item.waybillNo, {
                            margin: 4,
                            height: 75,
                        });
                        if (item.ordSubOrderDtos.length) {
                            item.ordSubOrderDtos.forEach(function(subItem) {
                                JsBarcode('#barcode_' + subItem.subOrderNo, subItem.subOrderNo, {
                                    margin: 4,
                                    height: 75,
                                });
                            })
                        }
                    })
                }
            })
        },

        destroyOrder: function () {
            var uploadSuccessful = window.localStorage.getItem("uploadSuccessful");
            if(uploadSuccessful !== "false"){
                this.setState({ orders: [] });
                this.setState({ showUploadFile: false });
                PromptComponent.init({}).close();
                document.body.style.overflowY = 'auto';
            }
        },

        getCurrentTime: function () {
            var date = new Date();
            var y = date.getFullYear();
            var m = date.getMonth()+1;
            var d = date.getDate();
            var HH = date.getHours() > 9 ? date.getHours() : '0' + date.getHours();
            var MM = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes();
            var SS = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
            var now = y + '/' + m + '/' + d + ' ' + HH + ':' + MM + ':' + SS;
            this.setState({ currentTime: now });
        },

        toggleTab: function (index) {
            if (this.state.active === index) return;
            this.setState({active: index });
            this.refs.form.reset();

            this.refs.beginDate.setValue(new Date().getBeforeDate(6)+' 00:00:00');
            this.refs.endDate.setValue(new Date().format("yyyy-MM-dd 23:59:59"));

            this.search({
                statusType: index,
                pageIndex: 1,
                startEffectTime:new Date().getBeforeDate(6)+' 00:00:00',
                endEffectTime:new Date().format("yyyy-MM-dd 23:59:59")
            });
            this.setState({ searchData: '', selectItem: [], selectLength: 0, current: 1 ,selectOrderStatus:[]})
        },

        submit: function (data) {
            this.refs.form.setFormPristine();
            var searchData;
            if (data.waybillNo && data.waybillNo.length) {
                searchData = { orderNo: data.waybillNo.trim() };
            } else if (data.cusOrderNo) {
                searchData = { cusOrderNo: data.cusOrderNo.trim() };
            } else {
                searchData = data;
            }
            searchData.startEffectTime = this.refs.beginDate.getValue();
            searchData.endEffectTime = this.refs.endDate.getValue();
            this.setState({ searchData: searchData, current: 1 });
            this.search(searchData);
        },
        resetForm: function () {
            this.refs.form.setFormPristine();
            this.refs.form.reset();

            this.refs.beginDate.setValue(new Date().getBeforeDate(6)+' 00:00:00');
            this.refs.endDate.setValue(new Date().format("yyyy-MM-dd 23:59:59"));

            this.setState({ searchData: '', current: 1 });
            this.search({
                pageIndex: 1,
                pageSize: 10 ,
                startEffectTime:new Date().getBeforeDate(6)+' 00:00:00',
                endEffectTime:new Date().format("yyyy-MM-dd 23:59:59")
            });
        },
        onPageChange: function (pageIndex, pageSize) {
            var param = {
                pageSize: pageSize,
                pageIndex: pageIndex,
                statusType: this.state.active,
                orderNo: this.state.searchData ? this.state.searchData.orderNo : '',
                cusOrderNo: this.state.searchData ? this.state.searchData.cusOrderNo : '',
                startEffectTime: this.state.searchData ? this.state.searchData.startEffectTime : new Date().getBeforeDate(6)+' 00:00:00',
                endEffectTime: this.state.searchData ? this.state.searchData.endEffectTime : new Date().format("yyyy-MM-dd 23:59:59")
            };
            this.setState({ pageSize: pageSize, current: pageIndex,selectItem:[],selectLength:0,selectOrderStatus:[]});
            this.search(param);
        },
        selectItemFn: function (item, e) {
            e.stopPropagation();
            var checked = e.target.checked,
                selectItem = this.state.selectItem,
                selectOrderStatus = this.state.selectOrderStatus,
                selectLength = this.state.selectLength,
                _this = this;
            if (item === 'all') {
                if (checked) {
                    selectItem = this.state.list.map(function(item) {
                        return item.orderNo;
                    });
                    selectOrderStatus= this.state.list.map(function(item) {
                        return item.orderStatus;
                    });
                    selectLength = this.state.list.length;
                } else {
                    selectItem = [];
                    selectOrderStatus = [];
                    selectLength = 0;
                }
            } else {
                if (checked) {
                    selectItem.push(item.orderNo);
                    selectOrderStatus.push(item.orderStatus);
                    selectLength += 1;
                } else {
                    var index = selectItem.indexOf(item.orderNo);
                    selectItem.splice(index, 1);
                    selectOrderStatus.splice(index, 1);
                    selectLength -= 1;
                }
            }
            this.setState({ selectItem: selectItem, selectLength: selectLength, selectOrderStatus:selectOrderStatus});
        },

        removeOrders: function () {
            var selectList = this.state.selectItem;
            if (!selectList.length) {
                PromptComponent.init({'type': 'warning', "msg":"请先选择数据！"}).show();
                return;
            }
            var _this = this;
            DialogComponent.init({
                'type':'delete',
                'msg':'确定删除？',
                'success':function(){
                    order_manageService.removeOrders(selectList, function (res) {
                        if (res.errorCode === 0) {
                            PromptComponent.init({
                                type: 'success',
                                msg: '操作成功'
                            }).show();
                            _this.setState({ selectItem: [], selectLength: 0 });
                            _this.search();
                        }else{
                            PromptComponent.init({
                                type: 'warning',
                                msg: res.msg
                            }).show();
                        }
                    })
                }
            }).show();
        },

        printOrders: function() {
            if (!this.state.selectLength) {
                PromptComponent.init({ type: 'warning', msg: '请选择至少选择一个订单进行打印' }).show();
                return;
            }
            this.getOrdersDetail(this.state.selectItem);
            document.body.style.overflowY = 'hidden';
        },

        uploadFile: function() {
            if (this.state.selectLength !== 1) {
                PromptComponent.init({ type: 'warning', msg: '请选择一个订单进行上传附件' }).show();
                return;
            }
            this.setState({showUploadFile: true,selectId:this.state.selectItem[0]});
            document.body.style.overflowY = 'hidden';
        },
        componentDidUpdate:function(){
            if(this.state.showUploadFile){
                this.getUploadFiles(this.state.selectId)
            }
        },

        getUploadFiles:function(id){
            var orderStatus= this.state.selectOrderStatus[0];
            var param = {
                system:'customer',
                edit:true,
                btnHandle:true,
                orderStatus:orderStatus,
                append:'#uploadFileContent',
                orderNo:id,
                orderFileType:{
                    url:'/api/v1/order/attaches/fileTypes',
                    type:'GET'
                },
                getOrderFile:{
                    url:'/api/v1/order/attaches',
                    type:'GET',
                    param:{
                        pageIndex:1,
                        pageSize:50,
                        orderNo:id
                    }
                },
                delOrderFile:{
                    url:'',
                    type:'POST',
                    param:{
                        orderNo:id,
                        orderFileId:''
                    }
                },
                addOrderFile:{
                    url:'/api/v1/order/attaches/'+id+'/orderFiles',
                    type:'POST',
                    param:{
                        orderNo:id,
                        orderFileId:''
                    }
                },
                ckeckFileName:{
                    url:'/api/v1/order/attaches/name/check',
                    type:'GET',
                    param:{
                        orderNo:id,
                        orderFileId:''
                    }
                },
                prompt:PromptComponent,
                dialog:DialogComponent
            };
            $(document).uploadBox(param)
        },

        confirmPrint: function () {
            $('.print-content').printArea();
        },

        render: function () {
            var Browser = typeof window != 'undefined',
                component = this;
            
            return ~init;
        }
    });
    if (typeof Object.assign != 'function') {
        Object.assign = function (target, varArgs) {
            'use strict';
            if (target == null) { // TypeError if undefined or null
                throw new TypeError('Cannot convert undefined or null to object');
            }
            var to = Object(target);
            for (var index = 1; index < arguments.length; index++) {
                var nextSource = arguments[index];
                if (nextSource != null) { // Skip over if undefined or null
                    for (var nextKey in nextSource) {
                        if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                            to[nextKey] = nextSource[nextKey];
                        }
                    }
                }
            }
            return to;
        };
    }
    if (typeof ReactDOM != "undefined") {
        ReactDOM.render(<PageComponent data={storage} />, document.getElementById('container'));
    }
    module.exports = PageComponent;
});
